<?php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use DB;
use App\Models\Invite;
use App\Models\InvitePoint;
use App\Models\User;
use App\Models\UserPoint;
use App\Models\UserCoupon;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        //
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        $schedule->call(function () {          
            $this->cancleInvite();
        })->everyFiveMinutes();
    }

    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__.'/Commands');

        require base_path('routes/console.php');
    }

    
    /**
     * 邀约超过七天过期
     */
    private function cancleInvite()
    {
        // 查询已到期的正在进行的拼团    
        $time = data('Y-m-d H:i:s',strtotime("-7 day"));
        $list = Invite::where('status',1)
            ->get();
            
        foreach ($list as $k => $v) {
            if($v->created_at>$time) continue;

            $ip = InvitePoint::where(['invite_id'=>$v->id])
                            ->first();
            if($ip) {
                $ip->status = 3;
                $ip->save();     
            }                
                           
            $user = User::find($ip->user_id);    
            $user->point        += object_get($ip,'point'); 
            $user->coupon_point += object_get($ip,'coupon_point');
            $user->save();

            // 被拒退还积分的记录
            if(object_get($ip,'point')>0){
                $up['user_id'] = $user->id;
                $up['point']   = $ip->point;
                $up['type']    = '-100';
                $up['remark']  = '邀约超时退还积分:'.$ip->point;
                UserPoint::create($up);    
            }
            
            if(object_get($ip,'coupon_point')>0) {
                // 被拒退还代金券
                $uc['user_id']      = $user->id;
                $uc['coupon_point'] = $ip->coupon_point;
                $uc['type'] = '-100';
                $uc['remark'] = '邀约超时退还代金券积分:'.$ip->coupon_point;
                UserCoupon::create($uc);    
            }

            $invite = Invite::find($v->id);
            $invite->status = '-100';
            $invite->save(); 
        }    

            
    }
}
